package com.fysports.web.event;

import com.google.common.collect.Maps;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.jfinal.log.Log;
import com.fysports.web.event.upload.UploadSubscribe;

import java.util.Map;
import java.util.concurrent.Executors;


/**
 * Class title: 事件总线工具类 <br/>
 * Describe:                    <br/>
 * Created by konbluesky           <br/>
 * Date : 15/12/29 下午7:22       <br/>
 * Project : weixin    <br/>
 */
public class EventKit {
    public static final String BUS_DEFAULT = "bus_default";
    private static Log logger = Log.getLog(EventKit.class);
    private static EventBus bus = null;
    private static final Map<String, EventBus> map = Maps.newHashMap();

    private EventKit() {
    }


    /**
     * plugin中初始化使用
     */
    public static void init(boolean isAsync) {
        if(isAsync){
            useAsync(BUS_DEFAULT);
        }else{
            use(BUS_DEFAULT);
        }

        /*========注册业务事件=== start =====*/
        //上传事件
        getBus().register(new UploadSubscribe());
        /*========注册业务事件=== end =====*/
    }

    public static EventBus use(String busname) {
        bus = map.get(busname);
        EventBus result = map.get(busname);
        if (result == null) {
            synchronized (map) {
                result = map.get(busname);
                if (result == null) {
                    result = new EventBus();
                    map.put(busname, result);
                    if (EventKit.bus == null)
                        EventKit.bus = result;
                }
            }
        }
        return result;
    }

    public static EventBus useAsync(String busname) {
        bus = map.get(busname);
        EventBus result = map.get(busname);
        if (result == null) {
            synchronized (map) {
                result = map.get(busname);
                if (result == null) {
                    result = new AsyncEventBus(busname, Executors.newFixedThreadPool(5));
                    map.put(busname, result);
                    if (EventKit.bus == null)
                        EventKit.bus = result;
                }
            }
        }
        return result;
    }

    public static EventBus getBus() {
        if (bus == null)
            throw new IllegalStateException(
                    "Load propties file by invoking EventKit.use(String busname) method first.");
        return bus;
    }


    public static void register(Object object){
        getBus().register(object);
    }
    public static void post(Object event){
        getBus().post(event);
    }
    public static void unregister(Object object){
        getBus().unregister(object);
    }
    public static void clean(){
        bus=null;
        map.clear();
    }

//    public static void main(String[] args) {
//        EventKit.init();
//        System.out.println(EventKit.getBus().toString());
//    }
}
